<style scoped lang="scss">
.time {
  font-size: 14px;
}

.content {
  font-weight: bold;
  padding-left: 5px;
}

.dashboard-editor-container {
  padding: 18px 22px 22px 22px;
  background-color: rgb(240, 242, 245);
  margin-bottom: 80px;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}

</style>

<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container">
      <el-card class="box-card" v-if="crud.optPageShow.listPage">
        <div slot="header" class="clearfix">
          <span>任务实例列表</span>
        </div>
        <!--工具栏-->
        <div class="head-container">
          <crudOperation :permission="permission" :defaultQueryForm="defaultQueryForm" :moreQueryList="moreQueryList"/>
        </div>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" v-if="!this.addDialog" :data="crud.data"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  style="width: 100%;" @select="crud.selectChange" @select-all="crud.selectAllChange"
                  @selection-change="crud.selectionChangeHandler"
                  @filter-change="crud.handleFilterChange"
                  :header-cell-style="{ background: 'rgba(52, 125, 225, 0.1)', color: '#404248' }" border stripe>
          <el-table-column v-if="false" prop="pkId" label="id"/>
          <el-table-column v-if="columns.visible('taskCode')" :show-overflow-tooltip="true" prop="taskCode"
                           label="任务编码"/>
          <el-table-column v-if="columns.visible('taskName')" :show-overflow-tooltip="true" prop="taskName"
                           label="任务名称"/>
          <el-table-column v-if="columns.visible('cronExpress')" :show-overflow-tooltip="true" min-width="100"
                           prop="cronExpress"
                           label="CRON表达式"/>
          <el-table-column v-if="columns.visible('execStTs')" :show-overflow-tooltip="true" min-width="160"
                           prop="execStTs"
                           label="执行开始时间"/>
          <el-table-column v-if="columns.visible('execEndTs')" :show-overflow-tooltip="true" min-width="160"
                           prop="execEndTs"
                           label="执行结束时间"/>
          <el-table-column v-if="columns.visible('costTs')" :show-overflow-tooltip="true" prop="costTs" label="耗时(秒)"/>
          <el-table-column v-if="columns.visible('batchTag')" :show-overflow-tooltip="true" prop="batchTag"
                           label="批次标签">
            <template slot-scope="scope">
              <el-tag size="medium" :type="success" v-if="scope.row.batchTag!=''&& scope.row.batchTag != null">
                {{ formatterBatchTag(scope.row.batchTag) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('execStatus')" prop="execStatus" label="执行状态 " min-width="100"
                           :filters="execStatusDict"
                           key="execStatus"
                           :filter-method="filterExecStatus" filter-placement="bottom-end" :filter-multiple="false"
                           column-key="execStatus">
            <template slot-scope="scope">
              <el-tag size="medium" style="width:60px;" :type="execStatusFormatterType(scope.row.execStatus)">
                {{ execStatusFormatter(scope.row.execStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="执行失败原因" v-if="columns.visible('execFailReason')" prop="execFailReason">
            <template slot-scope="scope">
              <el-button @click="lookErrorInf(scope.row)" v-if="'2' == scope.row.execStatus" type="text" size="small">
                查看原因
              </el-button>
            </template>
          </el-table-column>


        </el-table>
      </el-card>
    </div>
    <el-dialog title="失败原因" :visible.sync="dialogVisible" width="30%">
      <div style="max-height: 300px;overflow-y: auto">{{ errorInf }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 数据备份 -->
    <el-dialog append-to-body :close-on-click-modal="false" :visible.sync="crud.backUp" title="定时任务实例备份" width="680px">
      <el-form ref="form" :inline="true" :model="form" size="small" label-width="160px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="备份日期">
              <el-date-picker style="margin-left: 50px" v-model="backUpDate" type="date" value-format="yyyy-MM-dd"
                              placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-document-delete" @click="backUpCancel()">取消</el-button>
        <el-button icon="el-icon-document-add" type="primary" @click="backUpSubmit()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import cronTaskApi from '@/api/cronTask/cronTask'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import crudOperation from '@crud/extend/cronTask/cronTask/admin/CRUD.operation'
import backUp from '@/api/backUp/backUp'

const queryList = [{
  'cloumValue': 'taskCode',
  'cloumName': '任务编码'
}, {
  'cloumValue': 'taskName',
  'cloumName': '任务名称'
}, {
  'cloumValue': 'batchTag',
  'cloumName': '批次标签'
}];
const defaultCrud = CRUD({
  title: '任务实例',
  queryList: queryList,
  url: '/api/cronTask',
  queryOnPresenterCreated: false,
  sort: 'sort,asc',
  crudMethod: {
    ...cronTaskApi
  }
})
const defaultForm = {}

const tableColumnOptions = [];
export default {
  name: 'cron',
  components: {crudOperation},
  mixins: [presenter(defaultCrud), header(), form(), crud()],
  filters: {
    formatTime: function (value) {
      if (value != '') {
        return value.slice(0, 19).replace('T', ' ')
      }
    }
  },
  dicts: ['exec_status'],
  data() {
    return {
      backUpDate: "",
      dialogVisible: false,
      errorInf: '',
      active: 0,
      execType: '',
      permission: {
        backUp: ['cronTask:backUp']
      },
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      checkAll: true,
      tableColumns: tableColumnOptions,
      isIndeterminate: true,
      qryParam: '',
      qryCloum: '',
      showQryParamFlag: false,
      addDialog: false,
      rules: {},
      zones: ['linux', 'windows', 'ios'],
      uuidA: '',
      execDict: [],
      execStatusDict: [],
      defaultQueryForm: {
        taskCode: null,
        taskName: null,
        cronExpress: null,
        batchTag: null,
        appointAgentCode: null,
        execStatus: '',
        startTime: [],
        endTime: [],
        taskCodes: null
      },
      moreQueryList: [{
        cloumLable: 'taskCodes',
        name: "任务编码",
        type: 'textarea',
        placeholder: '可输入多个任务编码用,隔开',
        defaultValue: null
      },
        {
          cloumLable: 'taskName',
          name: "任务名称",
          type: 'input',
          placeholder: '',
          defaultValue: null
        },
        {
          cloumLable: 'cronExpress',
          name: "CRON表达式",
          type: 'input',
          placeholder: '',
          defaultValue: null
        },
        {
          cloumLable: 'execStatus',
          name: "执行状态",
          type: 'radio',
          placeholder: '',
          defaultValue: null,
          radioList: [{
            label: '',
            value: '全部'
          },
            {
              label: '2',
              value: '执行失败'
            },
            {
              label: '1',
              value: '执行成功'
            },
            {
              label: '3',
              value: '执行中'
            }
          ]
        },
        {
          cloumLable: 'startTime',
          cloumLableType: 'startTimeType',
          name: "执行开始时间",
          type: 'timeFramePicker',
          placeholder: '',
          defaultValue: null
        },
        {
          cloumLable: 'endTime',
          cloumLableType: 'endTimeType',
          name: "执行结束时间",
          type: 'timeFramePicker',
          placeholder: '',
          defaultValue: null
        },
      ],
    }
  },
  computed: {},
  created() {
    this.active = 0;
    this.initData()
    this.crud.updateProp('searchToggle', true)
    this.execDict = this.dict.exec_status;
    this.initQry()
  },
  watch: {
    execDict() {
      this.$nextTick(() => {
        this.execDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.execStatusDict.push(obj)
        })
      })
    },
  },
  methods: {
    initQry() {
      // this.crud.resetQuery()
      //alert(this.$route.query.pkId)
      //this.crud.resetQuery()
      this.crud.query.pkId = this.$route.query.pkId
      this.crud.toQuery()
    },
    execStatusFormatter(val) {
      return this.dict.label.exec_status[val]
    },
    execStatusFormatterType(val) {
      const type = ['', 'success', 'warning', 'primary', 'success', 'danger']
      return type[val]
    },
    backUpCancel() {
      this.crud.backUp = false
      this.backUpDate = ""
    },
    backUpSubmit() {
      var data = {
        "dateTs": this.backUpDate,
        "bitchType": "cron"
      }
      backUp.backUpData(data)
        .then(() => {
          this.$notify({
            title: '成功',
            message: '数据备份成功',
            type: 'success'
          });
          this.backUpDate = ""
          this.crud.backUp = false
          this.crud.query = {}
          this.crud.params = {}
          this.crud.toQuery()
        })
        .catch(() => {
          this.$notify.error({
            title: '错误',
            message: '数据备份异常'
          });
        });
    },
    formatterBatchTag(val) {
      return val;
    },
    lookErrorInf(data) {
      this.errorInf = data.execFailReason;
      this.dialogVisible = true;
    },
    filterExecStatus(value, row) {
      return row.execStatus === value;
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.$message({
          message: '请至少选择一列',
          type: 'warning'
        });
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(value) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.crud.props.tableColumns) {
        ++totalCount
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function () {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    },
    handleCheckAllChange(val) {
      this.checkedTableColumns = val ? tableColumnOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedTableColumnsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tableColumns.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableColumns.length;
    },
    showQryParams() {
      this.showQryParamFlag = true
    },
    hideQryParams() {
      this.showQryParamFlag = false
    },
    initData() {

    },
    add() {
      this.addDialog = true
    },
    update() {
    },
    del() {
    },
    backFun() {
      this.addDialog = false;
    },
  }
}
</script>
